<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import eventBus  from '../../event/eventBus.js';
import overlay_bg from '../../assets/image/overlay_bg.png'
import $ from 'jquery';
import { ElMessage } from "element-plus";
const NAME = '标绘';
const DOWN = '导出';

let isArea = ref(false);
const { appContext } = getCurrentInstance();
let global = appContext.config.globalProperties;

let tooltip = document.createElement('DIV');
document.body.appendChild(tooltip);
tooltip.style =
    'position: absolute;background: rgba(0,0,0,0.5); z-index: 999;line-height: 18px;pointer-events: none;';
tooltip.innerHTML =
    '<span style="color: #fff; font-size: 12px;padding:4px">单击开始，双击结束</span>'
tooltip.style.display = 'block'

let _handlers;
let _drawLayer;
let _last_clickTime;
let _last_clickPositionX;
let _last_clickPositionY;
let currOverlayArr = [];
let _drawLayerArr = [];
let _drawIndex = 0;
const positionHeight = 0;

onMounted(() => {
  eventBus.on('mapToolBarClick', (data) => {
    if(data == NAME){
      isArea.value = true;
      area()
    }else if(data == DOWN){
      // 导出
      let hasArea = false;
      _drawLayerArr.forEach(area => {
        if (area) {
          hasArea = true
        }
      })
      if (hasArea) {
        // 导出面
      } else {
        // ElMessage({
        //     message: '暂无标绘',
        //     type: 'warning'
        // })
      }
    }else{
      isArea.value = false;
      removeDistance();
    }
  });
});
// 空间面积
function area() {
    m_start() // 量算开启状态

    if (global.$viewer) {
        let positions = [],
            polygon = new Cesium.PolygonHierarchy(),
            _polygonEntity = new Cesium.Entity(),
            polyObj = null,
            _label = '';
        _handlers = new Cesium.ScreenSpaceEventHandler(global.$viewer.scene.canvas);

        const _addInfoPoint = function(position) {
            let result = Cesium.Measure.formatArea(Cesium.Measure.getArea(positions), 'auto');
            distanceOverlay(position, result)
        }
        //添加删除按钮
        const _addDeletePoint = function(position) {
            deleteOverlay(position)
        }

        const create = function() {
            _polygonEntity.polyline = {
                width: 3,
                material: Cesium.Color.fromCssColorString('#7FFF00'),
            }

            _polygonEntity.polyline.positions = new Cesium.CallbackProperty(function () {
                return positions
            }, false)

            _polygonEntity.polygon = {
                hierarchy: new Cesium.CallbackProperty(function () {
                    return polygon
                }, false),
                perPositionHeight: true,
                material: Cesium.Color.fromCssColorString('#7FFF00').withAlpha(0.4),
                opacity: 0.4,
                outline: true,
                outlineColor: Cesium.Color.fromCssColorString('#7FFF00')
            }
            _polygonEntity.clampToS3M = true

            polyObj = _drawLayer.entities.add(_polygonEntity)
            _drawLayerArr[_drawIndex] = polyObj;
        }
        // left
        _handlers.setInputAction(function (movement) {
            // 连续单击或者双击，不处理后面一个点
            if (isNearPoint(movement)) {
                return
            }

            let cartesian = pickPosition(movement.position);
            if (cartesian && cartesian.x) {
                if (positions.length == 0) {
                    polygon.positions.push(cartesian.clone())
                    positions.push(cartesian.clone());
                }
                positions.push(cartesian.clone());
                polygon.positions.push(cartesian.clone())

                if (!polyObj) create()
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

        // move
        _handlers.setInputAction(function (movement) {
            setTooltipPos(movement) // 设置tooltip位置
            let cartesian = pickPosition(movement.endPosition);
            if (positions.length >= 2) {
                if (cartesian && cartesian.x) {
                    positions.pop()
                    positions.push(cartesian);
                    polygon.positions.pop()
                    polygon.positions.push(cartesian);
                }
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

        // double-left
        _handlers.setInputAction(function (movement) {
            let cartesian = pickPosition(movement.position);
            m_end(); // 量算结束状态
            _addInfoPoint(positions[positions.length - 1])
            _addDeletePoint(cartesian)
        }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    }
}
// 测量结果的浮窗
function distanceOverlay(position, result) {
    if (global.$viewer) {
        let divStr = `<div class="overlay" style="position: absolute;width: auto;
                    height: auto;
                    background: url(${overlay_bg}) no-repeat 0 0 / 100% 100%;
                    font-size: 0.8rem;
                    padding: 0.5rem 0.8rem;
                    box-sizing: border-box;
                    color: #fff;">
                        <div class="name">${result}</div>
                    </div>`
        let element = $(divStr)[0];
        let currOverlay;
        let option = {
            element: element,
            position: position,
            offset: { //默认整个div的左上角，跟地图上指定的点重合
                x: -40, //向屏幕左边平移的像素值
                y: -40 //向屏幕下方平移的像素值
            }
        };
        currOverlay = new Cesium.Overlay(option);
        if (!currOverlayArr[_drawIndex]) {
            currOverlayArr[_drawIndex] = [];
        }
        currOverlayArr[_drawIndex].push(currOverlay)
        global.$viewer.addOverlay(currOverlay);
    }
}
// 删除结果的浮窗
function deleteOverlay(position) {
    if (global.$viewer) {
        let divStr = `<div class="overlay drawLine" index="${_drawIndex}" style="position: absolute;
                        font-size: 0.8rem;
                        box-sizing: border-box;
                        text-align: center;
                        line-height: 12px;
                        border-radius: 50%;
                        width: 16px;
                        height: 16px;
                        cursor: pointer;
                        border: 1px solid red;
                        background: #fff;
                        color: red;">x</div>`
        let element = $(divStr)[0];
        let currOverlay;
        let option = {
            element: element,
            position: position,
            offset: { //默认整个div的左上角，跟地图上指定的点重合
                x: 0, //向屏幕左边平移的像素值
                y: -10 //向屏幕下方平移的像素值
            }
        };
        currOverlay = new Cesium.Overlay(option);
        currOverlayArr[_drawIndex].push(currOverlay)
        global.$viewer.addOverlay(currOverlay);
        $('.drawLine').click(function() {
            let index = $(this).attr('index')
            // console.log(index)
            removeIndexDistance(+index)
        })
    }
}
function isNearPoint(movement) {
    let times = new Date().getTime() - (_last_clickTime || 0);
    if (_last_clickTime && times < 200) {
        // console.log('屏蔽了单击时间很近的点')
        return true;
    }
    _last_clickTime = new Date().getTime();

    if (
        _last_clickPositionX &&
        Math.abs(_last_clickPositionX - movement.x) < 10 &&
        Math.abs(_last_clickPositionY - movement.y) < 10
    ) {
        // console.log('屏蔽了单击像素很近的点')
        return true;
    }
    _last_clickPositionX = movement.x;
    _last_clickPositionY = movement.y;
    return false;
}
// 获取坐标
function pickPosition(position) {
    let ray = global.$viewer.camera.getPickRay(position);
    let c3 = global.$viewer.scene.globe.pick(ray, global.$viewer.scene);
    let cartographic= Cesium.Cartographic.fromCartesian(c3);
    let lat = Cesium.Math.toDegrees(cartographic.latitude);
    let lng = Cesium.Math.toDegrees(cartographic.longitude);
    let p = Cesium.Cartesian3.fromDegrees(lng, lat, positionHeight + 5);
    return p
}
function setTooltipPos(movement) {
    tooltip.style.left = movement.endPosition.x + 10 + 'px'
    tooltip.style.top = movement.endPosition.y - 27 + 'px'
}
function m_start() {
    if (global.$viewer) {
        if (!_drawLayer) {
            _drawLayer = new Cesium.CustomDataSource('drawLayer')
            global.$viewer.dataSources.add(_drawLayer);
        }
    }
    if (currOverlayArr[_drawIndex]) {
        _drawIndex++
    }    
    document.body.style.cursor = "crosshair"
    removeHandlers();
    showTooltip() // 显示tooltip提示
}
function m_end() {
    document.body.style.cursor = "default"
    removeHandlers();
    hideTooltip() // 隐藏tooltip提示
}
function removeHandlers() {
    _handlers && _handlers.destroy();
    _handlers = null;
}
function showTooltip() {
    tooltip.style.display = 'block'
}
function hideTooltip() {
    tooltip.style.display = 'none'
}
// 清除
function removeDistance() {
    if (_drawLayer) {
        _drawLayerArr.forEach(item => {
            _drawLayer.entities.remove(item)
        })
        _drawLayerArr = [];
    }
    if (currOverlayArr.length) {
        currOverlayArr.forEach(arr => {
            if (arr && typeof arr === 'object' && arr.length > 0) {
                arr.forEach(item => {
                    item.destroy();
                })
            }
        })
        currOverlayArr = [];
    }
    _drawIndex = 0;
    m_end()
}
function removeIndexDistance(index) {
    if (_drawLayer) {
        _drawLayer.entities.remove(_drawLayerArr[index])
        _drawLayerArr[index] = null;
    }
    if (currOverlayArr.length) {
        if (currOverlayArr[index] && currOverlayArr[index].length > 0) {
            currOverlayArr[index].forEach(item => {
                item.destroy();
            })
        }
        currOverlayArr[index] = null;
    }
}
</script>

<template >
  <div v-if="isArea"></div>
</template>